import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test108 {

    public static void main(String[] args) {
        Apple apple = new Apple();

        new Thread(() -> {
            for (int i = 0; i < 50; i++) apple.saleApple();
        }, "t1").start();

        new Thread(() -> {
            for (int i = 0; i < 50; i++) apple.saleApple();
        }, "t2").start();

        new Thread(() -> {
            for (int i = 0; i < 50; i++) apple.saleApple();
        }, "t3").start();

    }

}

class Apple {
    int num = 50;
    Lock lock = new ReentrantLock(true);

    void saleApple() {
        num--;
        lock.lock();
        if (num >= 0)
            System.out.println(Thread.currentThread().getName() + "卖出一个苹果，还剩" + num--);
        lock.unlock();
    }
}



// 演示可重入锁是什么意思，可重入，就是可以重复获取相同的锁，synchronized和ReentrantLock都是可重入的
// 可重入降低了编程复杂性
class WhatReentrant {
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    System.out.println("第1次获取锁，这个锁是：" + this);
                    int index = 1;
                    while (true) {
                        synchronized (this) {
                            System.out.println("第" + (++index) + "次获取锁，这个锁是：" + this);
                        }
                        if (index == 10) {
                            break;
                        }
                    }
                }
            }
        }).start();
    }
}
